package com.union.vehicleassistant.util;

import android.os.Build;
import android.text.Html;
import android.text.Spanned;

import androidx.annotation.RequiresApi;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HtmlUtils {

    @RequiresApi(api = Build.VERSION_CODES.N)
    public static Spanned removeEmptyTags(String html) {
        return Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT, s -> null, (opening, s, output, xmlReader) -> {
            if (!opening && output.length() > 0) {
                // 如果是闭合标签且输出内容不为空，检查是否为空标签
                int start = output.length();
                while (start > 0 && output.charAt(start - 1) == ' ') {
                    start--;
                }
                int end = output.length();
                String tagContent = output.subSequence(start, end).toString();
                if (tagContent.trim().isEmpty()) {
                    // 移除空标签
                    output.delete(start, end);
                }
            }
        });
    }

    /**
     * 去除富文本标签；
     * 用于判断是否空白内容
     *
     * @param htmlString 富文本内容
     * @return 去除标签后内容
     */
    public static String removeHtmlTags(String htmlString) {
        return Html.fromHtml(htmlString).toString().replaceAll("\\<.*?\\>", "");
    }

    public static String removeAllBank(String str, int count) {
        String s = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s{" + count + ",}|\t|\r|\n");
            Matcher m = p.matcher(str);
            s = m.replaceAll(" ");
        }
        return s;
    }
}